//
//  RFCryptoHelper.m
//  RFCryptoHelper
//
//  Created by 张岳鹏 on 2019/4/8.
//  Copyright © 2019 张岳鹏. All rights reserved.
//

#import "RFCryptoHelper.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "GlobalConst.h"
@interface RFCryptoHelper()
@property (nonatomic, strong) JSContext *jsContext;
@property (nonatomic, strong) JSValue * aesKeyValue;
@end

@implementation RFCryptoHelper
+ (instancetype)shared {
    static RFCryptoHelper *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[RFCryptoHelper alloc] init];
    });
    return shared;
}

- (JSContext *)contextFromJSFile {
    JSContext * context = [[JSContext alloc] initWithVirtualMachine: [[JSVirtualMachine alloc] init]];
    self.aesKeyValue = [context evaluateScript:@"Math.random().toString(36).slice(0, 20)"];
    NSString * test_path = [[NSBundle mainBundle] pathForResource:@"min" ofType:@"js"];
    NSString * test = [NSString stringWithContentsOfFile:test_path encoding:NSUTF8StringEncoding error:nil];
    [context evaluateScript:test];
    
    JSValue * setMaxDigits = [context objectForKeyedSubscript:@"setMaxDigits"];
    [setMaxDigits callWithArguments:@[@130]];
    return context;
}

-(NSDictionary *)enCrytedWidthPWD:(NSString *)pwd Exponent:(NSString *)exponent Modulus:(NSString *) modulus{
    NSMutableDictionary * result = [NSMutableDictionary dictionaryWithCapacity:2];
    JSContext * jsContext = [self contextFromJSFile];
    JSValue * aec_ctr = jsContext[@"Aes"][@"Ctr"][@"encrypt"];
    JSValue * enPwd = [aec_ctr callWithArguments:@[pwd, self.aesKeyValue.toString,@256]];
    
    JSValue * RSAKeyPair = jsContext[@"RSAKeyPair"];
    JSValue * rsaKey = [RSAKeyPair constructWithArguments:@[exponent, @"", modulus]];
    JSValue *  RSA_encryptedString = jsContext[@"RSA_encryptedString"];
    
    JSValue * encryptedKey = [RSA_encryptedString callWithArguments:@[rsaKey, self.aesKeyValue.toString]];
    
    [result setObject:enPwd.toString forKey:kENPWD];
    [result setObject:encryptedKey.toString forKey:kENCRYPTEDKEY];
    return result;
}
-(void *)enCrytedWidthPWD:(NSString *)pwd host:(NSString *)hostUrl callback:(void(^)(NSDictionary * result))callback{
    
    NSString * urlString = [hostUrl stringByAppendingString:@"/Handlers/JSProvider.ashx?encrypt=symmetric"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString * resp = @"";
        NSString *hexExponent = @"010001";
        NSString * modulus = @"";
        NSString *  secretToken = @"";
        //5.解析数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        if (dict == nil) {
            resp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSString * pattern = @"(?<==').*?(?=')";
            NSRegularExpression *regex =  [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
            
            //测试字符串
            NSArray *match = [regex matchesInString:resp options:0 range:NSMakeRange(0, resp.length)];
            NSMutableArray *rangeArr = [NSMutableArray array];
            // 取得所有的NSRange对象
            if(match.count != 0)
            {
                for (NSTextCheckingResult *matc in match)
                {
                    NSRange range = [matc range];
                    NSValue *value = [NSValue valueWithRange:range];
                    [rangeArr addObject:value];
                }
            }
            // 将要匹配的值取出来,存入数组当中
            __block NSMutableArray *mulArr = [NSMutableArray array];
            [rangeArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSValue *value = (NSValue *)obj;
                NSRange range = [value rangeValue];
                [mulArr addObject:[resp substringWithRange:range]];
                
            }];
            if(mulArr.count > 0){
                hexExponent = mulArr.firstObject;
                modulus = mulArr[1];
                secretToken = mulArr.lastObject;
            }
           NSDictionary * dic =  [self enCrytedWidthPWD:pwd Exponent:hexExponent Modulus:modulus];
            [dic setValue:secretToken forKey:kSECRETTOKEN];
            if (dic == nil) {
                dic = @{kENPWD:@"",kSECRETTOKEN:@"",kENCRYPTEDKEY:@""};
            }
            callback(dic);
        }
    }];
    
    //4.执行任务
    [dataTask resume];
    
    return nil;
}

@end
